import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '控制台', icon: 'House' }
      },
      {
        path: '/carousel',
        name: 'Carousel',
        component: () => import('@/views/carousel/Index.vue'),
        meta: { title: '轮播图管理', icon: 'Picture' }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/users/Index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: '/products',
        name: 'Products',
        component: () => import('@/views/products/Index.vue'),
        meta: { title: '产品管理', icon: 'Box' }
      },
      {
        path: '/tasks',
        name: 'Tasks',
        component: () => import('@/views/tasks/Index.vue'),
        meta: { title: '任务管理', icon: 'List' }
      },
      {
        path: '/settlements',
        name: 'Settlements',
        component: () => import('@/views/settlements/Index.vue'),
        meta: { title: '结算管理', icon: 'Money' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth !== false) {
    if (!authStore.token) {
      next('/login')
      return
    }

    // 如果有token但没有用户信息，获取用户信息
    if (!authStore.userInfo) {
      try {
        await authStore.getUserInfo()
        next()
      } catch (error) {
        authStore.logout()
        next('/login')
      }
    } else {
      next()
    }
  } else {
    // 登录页面，如果已登录则跳转到首页
    if (authStore.token) {
      next('/')
    } else {
      next()
    }
  }
})

export default router